<template>
  <a-form class="smart-query-form" v-privilege="'oa:enterprise:query'">
    <a-row class="smart-query-form-row">
      <a-form-item label="组织名称" class="smart-query-form-item">
        <a-input style="width: 300px" v-model:value="objFetch.orgName" placeholder="请输入名称" />
      </a-form-item>
      <a-form-item class="smart-query-form-item smart-margin-left10">
        <a-button-group>
          <a-button type="primary" @click="queryTable">
            <template #icon>
              <SearchOutlined />
            </template>
            查询
          </a-button>
          <a-button @click="resetQuery">
            <template #icon>
              <ReloadOutlined />
            </template>
            重置
          </a-button>
        </a-button-group>
      </a-form-item>
    </a-row>
  </a-form>
  <div class="height100">
    <a-row :gutter="16" class="height100">
      <a-col :span="6">
        <a-card class="tree-container" size="small">
          <a-directory-tree
            v-model:expandedKeys="expandedKeys"
            v-model:selectedKeys="selectedKeys"
            multiple
            :fieldNames="{ title: 'title', key: 'key', value: 'key' }"
            :tree-data="treeData"
            :defaultExpandAll="true"
            @select="treeSelectChange"
          ></a-directory-tree>
        </a-card>
      </a-col>

      <a-col :span="18" class="height100">
        <div class="help-doc-box height100">
          <a-card class="tree-container" size="small">
            <div class="smart-table-operate-block" style="display: flex">
              <a-button @click="addGoods" type="primary">
                <template #icon>
                  <PlusOutlined />
                </template>
                新建
              </a-button>

              <a-button type="primary" danger @click="deleterRecords" :disabled="selectedRowKeysarr.length == 0">批量删除</a-button>

              <a-button type="primary" @click="confirmBatchDelete">
                <template #icon>
                  <DownloadOutlined />
                </template>
                下载模板
              </a-button>

              <a-button @click="onExportGoods">
                <template #icon>
                  <ExportOutlined />
                </template>
                导出
              </a-button>

              <a-upload
                v-model:fileList="fileList"
                name="excelFile"
                :multiple="false"
                action="/maxkey-mgt-api/orgs/import"
                accept=".xls,.xlsx"
                @change="handleChange"
                :show-upload-list="false"
                :headers="headers"
              >
                <a-button>
                  <upload-outlined />
                  导入
                </a-button>
              </a-upload>
            </div>
            <a-table
              :dataSource="dataSource"
              :pagination="false"
              :columns="columns"
              bordered
              rowKey="id"
              :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'type'">
                  <span>
                    <a-tag v-if="record.type == 'group'"><span> 集团公司 </span></a-tag>
                    <a-tag v-if="record.type == 'company'"><span> 公司 </span></a-tag>
                    <a-tag v-if="record.type == 'division'"><span> 分支机构 </span></a-tag>
                    <a-tag v-if="record.type == 'department'"><span> 部门 </span></a-tag>
                    <a-tag v-if="record.type == 'team'"><span> 组 </span></a-tag>
                    <a-tag v-if="record.type == 'entity'"><span> 实体 </span></a-tag>
                    <a-tag v-if="record.type == 'virtual'"><span> 虚拟 </span></a-tag>
                  </span>
                </template>
                <template v-if="column.dataIndex === 'status'">
                  <span v-if="record.status == 1">
                    <check-circle-two-tone two-tone-color="#52c41a" />
                  </span>
                  <span v-else> </span>
                </template>

                <template v-if="column.dataIndex === 'action'">
                  <div class="smart-table-operate">
                    <a-button @click="updateRecord(record)" type="link">编辑</a-button>
                    <a-button danger @click="deleterRecord(record.id)" type="link">删除</a-button>
                  </div>
                </template>
              </template>
            </a-table>
            <div class="smart-query-table-page">
              <a-pagination
                showSizeChanger
                showQuickJumper
                show-less-items
                :pageSizeOptions="PAGE_SIZE_OPTIONS"
                :defaultPageSize="objFetch.pageSize"
                v-model:current="objFetch.pageNumber"
                v-model:pageSize="objFetch.pageSize"
                :total="total"
                @change="queryTable"
                @showSizeChange="queryTable"
                :show-total="(total) => `共${total}条`"
              />
            </div>
          </a-card>

          <a-modal v-model:open="open" :title="atitle" @ok="onSubmit" style="width: 50%">
            <!-- @ok="handleOk" -->
            <a-form ref="formRef" :model="formState" :rules="rules" :labelCol="{ span: 6 }">
              <a-tabs v-model:activeKey="activeKey">
                <a-tab-pane key="1" tab="基本信息">
                  <a-form-item label="组织编码" name="orgCode">
                    <a-input v-model:value="formState.orgCode" placeholder="请输入组织编码" />
                  </a-form-item>
                  <a-form-item label="组织名称" name="orgName">
                    <a-input v-model:value="formState.orgName" placeholder="请输入组织名称" />
                  </a-form-item>
                  <a-form-item label="组织全称" name="fullName">
                    <a-input v-model:value="formState.fullName" placeholder="请输入组织全称" />
                  </a-form-item>
                  <a-form-item label="类型" name="type">
                    <a-select v-model:value="formState.type" placeholder="请选择类型">
                      <a-select-option value="group">集团公司</a-select-option>
                      <a-select-option value="company">公司</a-select-option>
                      <a-select-option value="division">分支机构</a-select-option>
                      <a-select-option value="department">部门</a-select-option>
                      <a-select-option value="team">组</a-select-option>
                      <a-select-option value="entity">实体</a-select-option>
                      <a-select-option value="virtual">虚拟</a-select-option>
                    </a-select>
                  </a-form-item>
                  <a-form-item label="父级名称" name="parentId">
                    <!-- <a-select v-model:value="formState.parentId" v-for="i in treeData" placeholder="请选择父级名称">
                      <a-select-option :value="i.key">{{ i.title }}</a-select-option>
                    </a-select> -->
                    <a-tree-select
                      v-model:value="formState.parentId"
                      show-search
                      style="width: 100%"
                      :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                      placeholder="请选择父级名称"
                      allow-clear
                      :fieldNames="{ title: 'title', key: 'key', value: 'key' }"
                      tree-default-expand-all
                      :tree-data="treeData"
                      tree-node-filter-prop="title"
                    >
                      <template #title="{ value, title }">
                        <span>{{ title }}</span>
                      </template>
                    </a-tree-select>
                  </a-form-item>
                  <a-form-item label="排序" name="sortIndex">
                    <a-input v-model:value="formState.sortIndex" placeholder="请输入排序" />
                  </a-form-item>
                  <a-form-item label="状态" name="desc">
                    <a-switch
                      :checked-value="1"
                      :unchecked-value="0"
                      v-model:checked="formState.status"
                      placeholder="请选择状态"
                      @change="statusChange"
                    >
                      <template #checkedChildren><check-outlined /></template>
                      <template #unCheckedChildren><close-outlined /></template>
                    </a-switch>
                  </a-form-item>
                </a-tab-pane>

                <a-tab-pane key="2" tab="扩展信息" force-render>
                  <a-form-item label="编码路径" name="codePath">
                    <a-input v-model:value="formState.codePath" placeholder="请输入编码路径" />
                  </a-form-item>
                  <a-form-item label="名称路径" name="namePath">
                    <a-input v-model:value="formState.namePath" placeholder="请输入名称路径" />
                  </a-form-item>
                  <a-form-item label="级别" name="level">
                    <a-input v-model:value="formState.level" placeholder="请输入名称路径" />
                  </a-form-item>
                  <a-form-item label="分支机构" name="division">
                    <a-input v-model:value="formState.division" placeholder="请输入名称路径" />
                  </a-form-item>
                </a-tab-pane>

                <a-tab-pane key="3" tab="地址">
                  <a-form-item label="国家" name="country">
                    <a-input v-model:value="formState.country" placeholder="请输入国家" />
                  </a-form-item>
                  <a-form-item label="省/州" name="region">
                    <a-input v-model:value="formState.region" placeholder="请输入省/州" />
                  </a-form-item>
                  <a-form-item label="市" name="locality">
                    <a-input v-model:value="formState.locality" placeholder="请输入市" />
                  </a-form-item>
                  <a-form-item label="街道" name="street">
                    <a-input v-model:value="formState.street" placeholder="请输入街道" />
                  </a-form-item>
                  <a-form-item label="地址" name="address">
                    <a-input v-model:value="formState.address" placeholder="请输入地址" />
                  </a-form-item>
                </a-tab-pane>

                <a-tab-pane key="4" tab="联系方式">
                  <a-form-item label="联系人" name="contact">
                    <a-input v-model:value="formState.contact" placeholder="请输入联系人" />
                  </a-form-item>
                  <a-form-item label="联系电话" name="phone">
                    <a-input v-model:value="formState.phone" placeholder="请输入联系电话" />
                  </a-form-item>
                  <a-form-item label="电子邮箱" name="email">
                    <a-input v-model:value="formState.email" placeholder="请输入电子邮箱" />
                  </a-form-item>
                  <a-form-item label="传真" name="fax">
                    <a-input v-model:value="formState.fax" placeholder="请输入传真" />
                  </a-form-item>
                  <a-form-item label="邮政编码" name="postalCode">
                    <a-input v-model:value="formState.postalCode" placeholder="请输入邮政编码" />
                  </a-form-item>
                </a-tab-pane>

                <a-tab-pane key="5" tab="自定义字段">
                  <a-form-item label="教学地点" name="postalCode">
                    <a-input v-model:value="formState.extraAttrs" placeholder="请输入自定义字段" />
                    <!-- [{\"attr\":\"officeName\",\"name\":\"教学地点\",\"value\":\"上海崇明区\"}] -->
                  </a-form-item>
                </a-tab-pane>
              </a-tabs>
              <!-- <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
                <a-button type="primary" @click="onSubmit">Create</a-button>
                <a-button style="margin-left: 10px" @click="resetForm">Reset</a-button>
              </a-form-item> -->
            </a-form>
          </a-modal>
        </div>
      </a-col>
    </a-row>
  </div>
</template>

<script setup>
import { onMounted, onUnmounted, reactive, ref, toRaw, watch, nextTick, createVNode } from 'vue';
import { eduApi } from '/src/api/system/edu-api.js';
import { PAGE_SIZE, PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
import { smartSentry } from '/@/lib/smart-sentry';
import { Modal, message } from 'ant-design-vue';
import { SmartLoading } from '/src/components/framework/smart-loading';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { localRead } from '/@/utils/local-util';
import LocalStorageKeyConst from '/@/constants/local-storage-key-const.js';

const expandedKeys = ref(['1', '1-2']);
const selectedKeys = ref([]);
// const autoExpandParent = ref(true);
const treeData = ref([]);
const columns = [
  {
    title: '组织编码',
    dataIndex: 'orgCode',
    key: 'orgCode',
  },
  {
    title: '组织名称',
    dataIndex: 'orgName',
    key: 'orgName',
  },
  {
    title: '类型',
    dataIndex: 'type',
    key: 'type',
  },
  {
    title: '排序',
    dataIndex: 'sortIndex',
    key: 'sortIndex',
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
  },
  {
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
    width: 200,
  },
];

const objFetch = ref({
  orgName: '',
  orgName: '',
  parentId: '',
  parentName: '',
  startDate: '',
  endDate: '',
  startDatePicker: '1727771523149',
  endDatePicker: '1730363523149',
  pageSize: 10,
  pageNumber: 1,
  pageSizeOptions: 50,
});

const selectedRowKeysarr = ref([]);

const onSelectChange = (selectedRowKeys) => {
  selectedRowKeysarr.value = selectedRowKeys;
};

const dataSource = ref([]);
const total = ref(0);
const tableLoading = ref(false);
onMounted(() => {
  queryDepartmentTree();
  queryTable();
});

const formRef = ref();
const labelCol = {
  span: 5,
};
const wrapperCol = {
  span: 13,
};
const formState = ref({
  switch_status: '',
  status: '',
  sortIndex: '',
  switch_dynamic: 'false',
  type: '',
  orgCode: '',
  orgName: '',
  fullName: '',
  parentId: '',
  parentName: '',
  codePath: '',
  namePath: '',
  level: '',
  division: '',
  country: '',
  region: '',
  locality: '',
  street: '',
  address: '',
  contact: '',
  phone: '',
  email: '',
  fax: '',
  postalCode: '',
  extraAttrs: '',
});
const rules = {
  type: [{ required: true, message: '请选择', trigger: 'change' }],
};

const statusChange = (e) => {
  if (e == false) {
    formState.value.status = 0;
  } else {
    formState.value.status = 1;
  }
};
const onSubmit = () => {
  formRef.value
    .validate()
    .then(async () => {
      if (formState.value.status == false) {
        formState.value.status = 0;
      } else {
        formState.value.status = 1;
      }
      console.log(formState.value);
      // console.log('values', formState, toRaw(formState));
      // extraAttrs =[{\"attr\":\"officeName\",\"name\":\"教学地点\",\"value\":\"上海崇明区\"}]
      if (formState.value.id) {
        let res = await eduApi.orgsUpdate(formState.value);
        if (res.code == 0) {
          message.success('修改成功');
        } else {
          message.error('修改失败');
        }
      } else {
        for (let key in formState.value) {
          if (formState.value[key] === '') {
            delete formState.value[key];
          }
        }
        formState.value.switch_dynamic = false;
        formState.value.switch_status = true;
        let res = await eduApi.orgsAdd(formState.value);
        if (res.code == 0) {
          message.success('新增成功');
        } else {
          message.error('新增失败');
        }
      }

      open.value = false;
      queryTable();
    })
    .catch((error) => {
      console.log('error', error);
    });
};
const resetForm = () => {
  formRef.value.resetFields();
};

function deleterRecords() {
  Modal.confirm({
    title: '提醒',
    icon: createVNode(ExclamationCircleOutlined),
    content: '确定要删除吗?',
    okText: '删除',
    okType: 'danger',
    async onOk() {
      SmartLoading.show();
      try {
        await eduApi.orgsDeleteById(selectedRowKeysarr.value.join(','));
        queryTable();
        message.success('删除成功');
      } catch (error) {
        smartSentry.captureError(error);
        message.error('删除失败');
      } finally {
        SmartLoading.hide();
      }
    },
    cancelText: '取消',
    onCancel() {},
  });
}

// 删除
function deleterRecord(id) {
  Modal.confirm({
    title: '提醒',
    icon: createVNode(ExclamationCircleOutlined),
    content: '确定要删除吗?',
    okText: '删除',
    okType: 'danger',
    async onOk() {
      SmartLoading.show();
      try {
        await eduApi.orgsDeleteById(id);
        queryTable();
        message.success('删除成功');
      } catch (error) {
        smartSentry.captureError(error);
        message.error('删除失败');
      } finally {
        SmartLoading.hide();
      }
    },
    cancelText: '取消',
    onCancel() {},
  });
}
// 重置查询
function resetQuery() {
  objFetch.value.orgName = '';
  queryTable();
}
async function queryTable() {
  try {
    tableLoading.value = true;
    let res = await eduApi.getOrgsFetch(objFetch.value);
    dataSource.value = res.data.rows;
    total.value = res.data.records;
  } catch (err) {
    smartSentry.captureError(err);
  } finally {
    tableLoading.value = false;
  }
}

// ---------------------------- 添加/修改 ----------------------------
const formModal = ref();
const open = ref(false);
const atitle = ref('新增');

function updateRecord(val) {
  // console.log(val);
  atitle.value = '编辑';
  formState.value = val;
  open.value = true;
}

const addGoods = () => {
  for (let key in formState.value) {
    formState.value[key] = '';
  }
  // formState.value.status = true;
  formState.value.sortIndex = 1;
  formState.value.type = 'department';
  formState.value.parentId = objFetch.value.parentId;
  formState.value.parentName = objFetch.value.parentName;
  atitle.value = '新增';
  open.value = true;
};

const value = ref();
watch(value, () => {
  console.log(value.value);
});

// ------------------------------- 导出和导入 ---------------------------------
// 导入弹窗
const importModalShowFlag = ref(false);
const activeKey = ref('1');
const fileList = ref([]);

// 下载模板
async function confirmBatchDelete() {
  await eduApi.exportDownload();
}
//导出
async function onExportGoods() {
  await eduApi.exportDownloadOrg();
}

const useToken = localRead(LocalStorageKeyConst.USER_TOKEN);
const headers = {
  authorization: 'Bearer ' + useToken,
  Token: useToken,
  authserver: 'MaxKey',
};

const handleChange = (info) => {
  if (info.file.status !== 'uploading') {
    console.log(info.file, info.fileList);
  }
  if (info.file.status === 'done') {
    queryDepartmentTree();
    queryTable();
    message.success(`${info.file.name} 导入成功`);
  } else if (info.file.status === 'error') {
    // message.error('导入失败');
    message.error(`${info.file.name} 导入失败`);
  }
};

// 查询部门列表并构建 部门树
async function queryDepartmentTree() {
  let res = await eduApi.getOrgsTree();
  nextTick(() => {
    treeData.value = buildTree(res.data.nodes);
  });
}

function treeSelectChange(idList, info) {
  const stringId = idList.join('');
  objFetch.value.parentId = stringId;
  objFetch.value.parentName = info.node.title;
  queryTable();
}

function buildTree(data) {
  const tree = [];
  const map = {};
  // 先把所有节点放入一个映射表
  data.forEach((item) => {
    // map[item.key] = { ...item, children: [] };
    map[item.key] = { title: item.title, key: item.key, parentKey: item.parentKey, children: [] };
  });

  // 构建树
  data.forEach((item) => {
    const { parentKey } = item;
    if (parentKey === '0') {
      // 如果是根节点
      tree.push(map[item.key]);
    } else {
      // 如果有父节点，则将当前节点添加到父节点的 children 中
      if (map[parentKey]) {
        map[parentKey].children.push(map[item.key]);
      }
    }
  });
  return tree;
}
onUnmounted(() => {});
</script>

<style scoped lang="less">
/** @format */
.smart-table-operate-block {
  .ant-btn {
    margin: 0 12px 8px 0;
  }
}
.height100 {
  height: 100%;
}

.help-doc-box {
  display: flex;
  flex-direction: column;

  .employee {
    flex-grow: 2;
    margin-top: 10px;
  }
}

.tree-container {
  height: 100%;

  .tree {
    height: 618px;
    margin-top: 10px;
    overflow-x: hidden;
  }

  .sort-flag-row {
    margin-top: 10px;
    margin-bottom: 10px;
  }

  .sort-span {
    margin-left: 5px;
  }

  .no-data {
    margin: 10px;
  }
}
</style>